<?php

namespace App\Components;

use App\Components\Tools;
use App\Models\DyModels\DyuserQyhFans;
use App\Models\DyModels\DyuserQyhVideo;
use App\Models\DyModels\Douyin;

/**
 * 抖音工具类
 */
class DySqTools
{
    //抖音调用接口方法
    private $clientKey = '';
    private $clientSecret = '';
    private $url = '';
    private $redirectUri = '';
    private $scope = '';

    function __construct()
    {
        $this->clientKey = Tools::getOneconfig("/config/third.json", array('douyin', 'dy_client_key'));
        $this->clientSecret = Tools::getOneconfig("/config/third.json", array('douyin', 'dy_client_secret'));
        $this->url = Tools::getOneconfig("/config/third.json", array('douyin', 'dy_url'));
        $this->redirectUri = Tools::getOneconfig("/config/third.json", array('douyin', 'dy_bank_url'));

        $this->scope = 'video.create,video.delete,video.data,video.list,im.share,video.search,video.search.comment,aweme.share,user_info,';
        $this->scope .= 'following.list,fans.list,fans.check,renew_refresh_token,mobile_alert,mobile,video.comment,enterprise.data,enterprise.im,';
        $this->scope .= 'item.comment,data.external.user,data.external.item,fans.data,star_top_score_display,star_tops,star_author_score_display,';
        $this->scope .= 'data.external.sdk_share,data.external.fans_favourite,poi.search,micapp.is_legal,incremental_authorization';
    }

    /**    刷新access_token
     *    流程 ： 其他接口返回 2190008 或 10008   需要调用此方法
     *    如果此方法返回  10010    需要调用 refresh_token  方法刷新
     */
    function refresh_token($refresh_token)
    {
        $url = $this->url . "/oauth/refresh_token?client_key={$this->clientKey}&grant_type=refresh_token&refresh_token={$refresh_token}";
        $data = $this->getJson($url);
        return $data;
    }

    //刷新refresh_token  不需要授权
    function renew_refresh_token($refresh_token)
    {
        $url = $this->url . "/oauth/renew_refresh_token?client_key={$this->clientKey}&refresh_token={$refresh_token}";
        $data = $this->getJson($url);
        return $data;
    }

//生成client_token  不需要授权 2小时有效
    function client_token()
    {
        $url = $this->url . "/oauth/client_token/";
        $postData = [
            'client_key' => $this->clientKey,
            'client_secret' => $this->clientSecret,
            'grant_type' => 'client_credential',
        ];
        $data = $this->postJson($url, $postData);
        return $data;
    }

    //生成cltoken
    function createcltoken()
    {
        $DyToools = new DyToools();
        $clienttk = $DyToools->client_token();
        return $clienttk;
    }

    //方法汇总
    function getAllInfo($openid, $access_token, $refresh_token)
    {
        if (!empty($openid)) {
            $this->getMoreVideolist($openid, $access_token, 0);
            $this->getEnterpriseinfo($openid, $access_token, $refresh_token);
            $this->getFansData($openid, $access_token, $refresh_token, 0);
            $this->getFollowingData($openid, $access_token, $refresh_token, 0);
            $this->getEnterpriseData($openid, $access_token, $refresh_token, 1);
        }
    }

    //获取所有的视频的方法
    function getMoreVideolist($open_id, $access_token, $cursor)
    {
        $soDyuserQyhVideo = new DyuserQyhVideo();
        $url = $this->url . "/video/list/?open_id=$open_id&access_token=$access_token&cursor=$cursor&count=20";//获取近一个月的视频
        $data = $this->getJson($url);
     //   print_r($data);exit();
        if ($data['data']['has_more'] == 1 ) {
            //先数据入库然后再次调用自己
            $soDyuserQyhVideo->saveVideoInfo($data['data']['list'], $open_id);
            $this->getMoreVideolist($open_id, $access_token, $data['data']['cursor']);
        } else {
            if(empty($data['data']['list'])){
                echo "授权成功";
            }else{
                $soDyuserQyhVideo->saveVideoInfo($data['data']['list'], $open_id);
            }

        }
    }

    //获取企业用户视频数据
    function getEnterpriseinfo($openid, $access_token, $refresh_token)
    {
        $soDyuserQyhVideo = new DyuserQyhVideo();
        $infoToken = new Douyin();
        $DyToools = new DyToools();
        if (!empty($access_token)) {
            $url = $this->url . "/video/list/?open_id=$openid&access_token=$access_token&count=20";//获取近一个月的视频
            $data = $this->getJson($url);
            if ($data['extra']['error_code'] == 0) {
                // 返回值正确的话  数据入库
                $soDyuserQyhVideo->saveVideoInfo($data['data']['list'], $openid);
                if ($data['data']['has_more'] == 1) {
                    //如果还有更多视频没拉取调用方法拉取
                    $this->getMoreVideolist($openid, $access_token, $data['data']['cursor']);//如果有就调用函数把所有的数据都抓取出来
                }
            } elseif (isset($dataList['data']['error_code']) && ($dataList['data']['error_code'] == 10008 || $dataList['data']['error_code'] == 2190008)) {
                //授权过期刷新access_token然后继续
                $ass = $this->refresh_token($refresh_token);//刷新access——token
                $infoToken->upToken($ass['data'], $openid);//更新数据库的信息
                //重新调用获取数据的方法
                if ($ass['data']['error_code'] == 0) { //如果返回值正确就进行接口调用
                    $url = $this->url . "/video/list/?open_id=$openid&access_token={$ass['data']['access_token']}&count=20";//获取近一个月的视频
                    $date = $this->getJson($url);
                    if ($date['extra']['error_code'] == 0) {// 返回值正确的话  数据入库
                        $soDyuserQyhVideo->saveVideoInfo($date['data']['list'], $openid);
                        if ($date['data']['has_more'] == 1) {
                            //如果还有更多视频没拉取调用方法拉取
                            $this->getMoreVideolist($openid, $ass['data']['access_token'], $date['data']['cursor']);//如果有就调用函数把所有的数据都抓取出来
                        }
                    }
                } elseif (isset($ass['data']['error_code']) && $ass['data']['error_code'] == 10010) {//如果之前刷新也失败返回这个就调用方法目前无效 需重新授权
                    //refresh_token 过期
                    $dataTwo = $DyToools->renew_refresh_token($refresh_token);//刷新refresh_token
                    if (isset($data['data']['error_code']) && $dataTwo['data']['error_code'] == 0) {
                        //更新数据库的 refresh_token
                        $infoToken->upRef($dataTwo['data'], $openid);
                        //用新的来更新access_token 然后继续调用数据获取下视频数据
                        $acss = $this->refresh_token($dataTwo['data']['refresh_token']);//刷新access——token
                        $infoToken->upToken($acss['data'], $openid);//更新数据库的信息
                        $urel = $this->url . "/video/list/?open_id=$openid&access_token={$acss['data']['access_token']}&count=20";//获取近一个月的视频
                        $datt = $this->getJson($urel);
                        if ($datt['extra']['error_code'] == 0) {// 返回值正确的话  数据入库
                            $soDyuserQyhVideo->saveVideoInfo($datt['data']['list'], $openid);
                            if ($datt['data']['has_more'] == 1) {
                                //如果还有更多视频没拉取调用方法拉取
                                $this->getMoreVideolist($openid, $acss['data']['access_token'], $datt['data']['cursor']);//如果有就调用函数把所有的数据都抓取出来
                            } else {
                                $infoToken->upTokenStatus($openid);//授权过期需用户重新授权 更改授权状态 为 0
                            }
                        }
                    }
                }
            }
        }
    }

//粉丝数据
    function getFansData($open_id, $access_token, $refresh_token, $cursor)
    {
        $soFans = new DyuserQyhFans();
        $infoToken = new Douyin();
        $DyToools = new DyToools();
        $url = $this->url . "/fans/list/?open_id=$open_id&access_token=$access_token&cursor={$cursor}&count=20";
        //echo '<pre/>';	 print_r($url);
        $data = $this->getJson($url);
        if (isset($data['extra']['error_code']) && $data['extra']['error_code'] == 0) {
            if (isset($data['data']['list']) && $data['data']['list']) {
                //更新、添加用户粉丝数据
                $soFans->upDyUserFans($data['data']['list'], $open_id);
            }
            if ($data['data']['cursor'] > 0 && $data['data']['has_more']) {
                $this->getFansData($open_id, $access_token, $refresh_token, $data['data']['cursor']);
            }
        } elseif (isset($data['extra']['error_code']) && $data['extra']['error_code'] == 10008 || $data['extra']['error_code'] = 2190008) {
            // access_token 过期
            $dataOne = $DyToools->refresh_token($refresh_token);
            if (isset($dataOne['data']['error_code']) && $dataOne['data']['error_code'] == 0) {
                $infoToken->upToken($dataOne['data'], $open_id);//更新Token
                $this->getFansData($open_id, $access_token, $refresh_token, $cursor);
            } elseif (isset($dataOne['data']['error_code']) && $dataOne['data']['error_code'] == 10010) {
                //refresh_token 过期
                $dataTwo = $DyToools->renew_refresh_token($refresh_token);
                if (isset($dataTwo['data']['error_code']) && $dataTwo['data']['error_code'] == 0) {
                    $infoToken->upRef($dataTwo['data'], $open_id);//更新refresh_token
                    $this->getFansData($open_id, $access_token, $refresh_token, $cursor);
                } else {
                    $infoToken->upTokenStatus($open_id);//授权过期需用户重新授权 更改授权状态 为 0
                }
            }
        }
    }

    //关注数据
    function getFollowingData($open_id, $access_token, $refresh_token, $cursor)
    {
        $userToken = new DyuserQyhFans();
        $infoToken = new Douyin();
        $DyToools = new DyToools();

        $url = $this->url . "/following/list/?open_id=$open_id&access_token=$access_token&cursor={$cursor}&count=20";
        $data = $this->getJson($url);
        if (isset($data['extra']['error_code']) && $data['extra']['error_code'] == 0) {
            if (isset($data['data']['list']) && $data['data']['list']) {
                //更新、添加用户关注数据
                $userToken->upDyUserFollowing($data['data']['list'], $open_id);
            }
            if ($data['data']['cursor'] > 0 && $data['data']['has_more']) {
                $this->getFollowingData($open_id, $access_token, $refresh_token, $data['data']['cursor']);
            }
        } elseif (isset($data['extra']['error_code']) && $data['extra']['error_code'] == 10008 || $data['extra']['error_code'] = 2190008) {
            // access_token 过期
            $dataOne = $DyToools->refresh_token($refresh_token);
            if (isset($dataOne['data']['error_code']) && $dataOne['data']['error_code'] == 0) {
                $infoToken->upToken($dataOne['data'], $open_id);//更新Token
                $this->getFollowingData($open_id, $access_token, $refresh_token, $cursor);
            } elseif (isset($dataOne['data']['error_code']) && $dataOne['data']['error_code'] == 10010) {
                //refresh_token 过期
                $dataTwo = $DyToools->renew_refresh_token($refresh_token);
                if (isset($dataTwo['data']['error_code']) && $dataTwo['data']['error_code'] == 0) {
                    $infoToken->upRef($dataTwo['data'], $open_id);//更新refresh_token
                    $this->getFollowingData($open_id, $access_token, $refresh_token, $cursor);
                } else {
                //    print_r(1111);
                    $infoToken->upTokenStatus($open_id);//授权过期需用户重新授权 更改授权状态 为 0
                }
            }

        }
    }

    //  获取意向客户的方法
    function getEnterpriseData($open_id, $access_token, $refresh_token, $cursor)
    {//
        $userToken = new DyuserQyhFans();
        $infoToken = new Douyin();
        $DyToools = new DyToools();
        $start_time = strtotime("-1 year -0 month -0 day");//int类型 时间戳吧 设定一年内有互动的都获取
        $end_time = time();//int类型 结束时间
        $url = $this->url . "/enterprise/leads/user/list/?open_id=$open_id&access_token=$access_token&cursor={$cursor}&count=20";
        $url .= "&start_time=$start_time&end_time=$end_time&action_type=0";
        $data = $this->getJson($url);
        //echo '<pre/>'; print_r($data);
        if (isset($data['data']['error_code']) && $data['data']['error_code'] == 0) {
            if (isset($data['data']['users']) && $data['data']['users']) {
                //更新、添加用户意向客户
                $userToken->upDyUserEnterprise($data['data']['users'], $open_id);
            }
            if ($data['data']['cursor'] > 0 && $data['data']['has_more']) {
                $this->getEnterpriseData($open_id, $access_token, $refresh_token, $data['data']['cursor']);
            }
        } elseif (isset($data['data']['error_code']) && $data['data']['error_code'] == 10008 || $data['data']['error_code'] = 2190008) {
            // access_token 过期
            $dataOne = $DyToools->refresh_token($refresh_token);
            if (isset($dataOne['data']['error_code']) && $dataOne['data']['error_code'] == 0) {
                $infoToken->upToken($dataOne['data'], $open_id);//更新Token
                $this->getEnterpriseData($open_id, $access_token, $refresh_token, $cursor);
            } elseif (isset($dataOne['data']['error_code']) && $dataOne['data']['error_code'] == 10010) {
                //refresh_token 过期
                $dataTwo = $DyToools->renew_refresh_token($refresh_token);
                if (isset($dataTwo['data']['error_code']) && $dataTwo['data']['error_code'] == 0) {
                    $infoToken->upRef($dataTwo['data'], $open_id);//更新refresh_token
                    $this->getEnterpriseData($open_id, $access_token, $refresh_token, $cursor);
                } else {
                    $infoToken->upTokenStatus($open_id);//授权过期需用户重新授权 更改授权状态 为 0
                }
            }

        }
    }


    //get请求
    function getJson($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);//为true，则会跟踪爬取重定向页面，否则，不会跟踪重定向页面
        $output = curl_exec($ch);
        curl_close($ch);
        return json_decode($output, true);
    }

    //post请求
    function postJson($url, $data = array())
    {
        //初始化
        $curl = curl_init();
        //设置抓取的url
        curl_setopt($curl, CURLOPT_URL, $url);
        //设置头文件的信息作为数据流输出
        curl_setopt($curl, CURLOPT_HEADER, 0);
        //超时时间
        curl_setopt($curl, CURLOPT_TIMEOUT, 60);
        //设置获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        //设置post方式提交
        curl_setopt($curl, CURLOPT_POST, 1);
        //设置post数据
        curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); //不验证证书下同
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json',
                'Content-Length: ' . strlen(json_encode($data)))
        );
        //执行命令
        $json = curl_exec($curl);
        //关闭URL请求
        curl_close($curl);
        return json_decode($json, true);
    }

}